using System;
using System.IO;
using System.Reflection;
using System.Collections;

using umbSearch.interfaces;

namespace umbSearch.businessLogic
{
	/// <summary>
	/// Summary description for FileFilterFactory.
	/// </summary>
	public class FileFilterFactory
	{
		private static bool _isInitialized = false;
		private static System.Collections.Hashtable _filters = new System.Collections.Hashtable();

		public FileFilterFactory()
		{
		}

        public static IUmbracoSearchFileFilter GetFilter(string extension) 
		{
			if (!_isInitialized)
				init();

			IDictionaryEnumerator ide = _filters.GetEnumerator();
			while (ide.MoveNext()) 
			{
				if (ide.Key.ToString().IndexOf(extension) > -1)
                    return Activator.CreateInstance(ide.Value.GetType()) as interfaces.IUmbracoSearchFileFilter;
			}

            throw new Exception(String.Format("No filter found matching extension {0}. Loaded and valid extensions includes: {1}", extension, GetLoadedFilterExtensions()));
		}

		private static void init() 
		{

			string _pluginFolder = "/bin";

            foreach (string assembly in System.IO.Directory.GetFiles(System.Web.HttpContext.Current.Server.MapPath(_pluginFolder), "*.dll")) 
			{
				try 
				{
					Assembly asm = System.Reflection.Assembly.LoadFrom(assembly);
					try 
					{
						foreach (Type t in asm.GetTypes()) 
						{
							Type hasInterface = t.GetInterface("umbSearch.interfaces.IUmbracoSearchFileFilter", true);

							if (hasInterface != null && !t.IsInterface) 
							{
							
								IUmbracoSearchFileFilter typeInstance = Activator.CreateInstance(t) as IUmbracoSearchFileFilter;
								string extensions = ",";
								foreach(string ext in typeInstance.extensions)
									extensions += ext + ",";
								_filters.Add(extensions,typeInstance);
								System.Web.HttpContext.Current.Trace.Write("datatype.factory", " + Adding datatype for extensions '" + extensions + "'");
							} 
						}
					} 
					catch (Exception factoryE) 
					{
						System.Web.HttpContext.Current.Trace.Warn("umbSearch.FileFilterFactory", "error", factoryE);
					}
				} 
				catch 
				{
					System.Web.HttpContext.Current.Trace.Warn("umbSearch.FileFilterFactory", "Couldn't load " + assembly);
				}
			}
			_isInitialized = true;

		}

        public static string GetLoadedFilterExtensions() {
            if (!_isInitialized)
                init();

            string filterList = "";

            IDictionaryEnumerator ide = _filters.GetEnumerator();
            while (ide.MoveNext())
                filterList += ide.Key.ToString().Substring(1, ide.Key.ToString().Length-2).Replace(",", ", ") + ", ";

            if (filterList.Length > 0)
                return filterList.Substring(0, filterList.Length - 2);
            else
                return "";
        }


    }


}
